package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.result.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.applet.AppletStub;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Author : mayp
 * @Date: 2020-09-21 12:34
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;
    /**
     * es检索
     * @param param
     * @return
     */
    @Override
    public SearchResult search(SearchParam param) {
        SearchResult result = null;
//        1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
//        2、执行检索请求
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
//        3、封装响应数据
            result = buildSearchResponse(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("result = " + result);
        return result;
    }

    /**
     * 请求检索数据的封装
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
//        构建DSL查询语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 准备检索请求
         *  模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
         */
//        1、构建bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        1.1、must-模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
//        1.2、filter-term 三级分类id精确查找
        if (null != param.getCatalog3Id()){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
//        1.3、filter-terms 品牌id精确查询
        if (null != param.getBrandId() && param.getBrandId().size() > 0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
//        1.4、根据商品属性查询
        if (null != param.getAttrs() && param.getAttrs().size() > 0){
            /**
             * 拿到的数据格式
             * attrs=1_5寸:8寸&attrs=2_16G:8G
             */
            for (String attrStr : param.getAttrs()){
                BoolQueryBuilder nesteBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
//                检索的属性id
                String attrId = s[0];
//                检索属性值
                String[] attrValues = s[1].split(":");
                nesteBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nesteBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
//                每一个都组装一个查询条件
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nesteBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
//        1.5、根据是否有库存查询
        if (param.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",param.getHasStock() == 1));
        }
//        1.6、根据价格区间查询
        if (!StringUtils.isEmpty(param.getSkuPrice())){
            /**
             * 数据格式
             * 1_500/_500/500_
             *
             * "range":{
             *     "skuPrice":{
             *         "gte":0,
             *         "lte":400
             *     }
             * }
             */
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
//            切割字符串，获取价格区间([1,500],[500],[500])
            String[] s = param.getSkuPrice().split("_");
//            判断是否有最低价与最高价
            if (s.length == 2){
//                大于第一个，小于第二个
                rangeQuery.gte(s[0]).lte(s[1]);
            }else if (s.length == 1){ // 没有最大值或最小值。
//                最大值('_'在前面说明最大值)
                if (param.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(s[0]);
                }
//                最小值('_'在后面说明最小值)
                if (param.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

//        查询条件的封装
        sourceBuilder.query(boolQuery);

        /**
         * 排序，分页，高亮
         */
//        2、排序
//        2.1、组装排序条件
        if (!StringUtils.isEmpty(param.getSort())){
//            sort=saleCount_asc/desc
            String[] s = param.getSort().split("_");
//            第一个是排序字段，第二个是升序还是降序
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0],sortOrder);
        }
//        2.2、分页
        sourceBuilder.from((param.getPageNum()-1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
//        2.3、高亮
        if (!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        /**
         * 聚合分析
         */
//        分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        // 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
//        品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        sourceBuilder.aggregation(brand_agg);

//        属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
//        聚合出当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
//        1、属性名称聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
//        2、属性值聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
//        把当前的属性聚合在attr_agg中
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);
        String s = sourceBuilder.toString();
        System.out.println("构建的DSL = " + s);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);
        return searchRequest;
    }

    /**
     * 响应检索数据的封装
     * @return
     */
    private SearchResult buildSearchResponse(SearchResponse response,SearchParam param) {
        SearchResult result = new SearchResult();
//        1、返回所有查询的结果数据
//          1.1、响应的总记录
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0){
            for (SearchHit hit : hits){
//                每条结果集
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
//                高亮设置
                if (!StringUtils.isEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }
                 esModels.add(esModel);
            }
        }
        result.setProducts(esModels);

//        2、当前所有商品涉及到的所有属性信息(该聚合数据嵌入式聚合)
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
//            1、得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
//            2、得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
//            3、得到属性的值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = (item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());

            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

//        3、当前所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()){
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
//            1、得到品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
//            2、得到品牌名称
            String brandName = ((ParsedStringTerms)bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
//            3、得到品牌图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

//        4、当前所有商品涉及到的所有分类信息
//          4.1、根据聚合名字获得聚合信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
//        用来封装分类信息的集合，最后放到result.setCatalogs(catalogVos);
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
//        4.2、得到所有buckts信息
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
//        遍历buckets信息，得到每一条分类信息
        for (Terms.Bucket bucket : buckets){
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
//            得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
//            得到分类名称(根据es查询出来的名字获取),转换成ParsedStringTerms
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
//            封装到分类结果集合中
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
//#############################以上是聚合信息###################################
//        5、分页信息-页码
        result.setPageNum(param.getPageNum());
//        6、分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
//        7、分页信息-总页码
        int totalPages = (int)total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int)total / EsConstant.PRODUCT_PAGESIZE : (int)(total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i =1; i<=totalPages;i++){
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

//        8、构建面包屑导航
        if (param.getAttrs() != null && param.getAttrs().size() > 0){
            List<SearchResult.NavVo> navVos = param.getAttrs().stream().map(attr -> {
//            1、分析每一个attrs传过来的查询参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
//            attrs=2_5寸：6寸
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.getAttrsInfo(Long.parseLong(s[0]));
                if (0 == r.getCode()){
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                }else{
                    navVo.setNavName(s[0]);
                }

//          2、取消了这个面包屑以后，需要跳转到那个地方，将请求地址的url里面的当前置空
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr,"UTF-8");
                    encode.replace("+","%20");// 浏览器对空格的编码
                }catch (UnsupportedEncodingException e){
                    e.printStackTrace();
                }
                String replace = param.get_queryString().replace("&attrs="+encode,"");
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }
        //    品牌，分类
        if (param.getBrandId() != null && param.getBrandId().size() > 0){
            List<SearchResult.NavVo> navVos = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
//            查询所有品牌
            R info = productFeignService.info(param.getBrandId());
//            navVo.setNavValue();
            navVos.add(navVo);
        }

        return result;
    }

}
